<?php
class PayController extends Controller
{
    protected $_log_key = null;
    protected function _log($info = null)
    {
        if($this->_log_key === null){
            $this->_log_key = create_uuid();
        }

        $log_file = dirname(__FILE__) . '/logs/wxcallback.'.date('ymd').'.log';

        $info = empty($info)? '' : $info;
        $info = date('Y-m-d H:i:s - ')  . '('.$this->_log_key.')' . $info . "\n";

        $handler = fopen($log_file, 'a+');
        fputs($handler, $info);
        fclose($handler);
    }

    public $layout = '//layouts/basic';

    public function actionScan()
    {
        $mno = app()->request->getParam('mno', null);
        $tno = app()->request->getParam('tno', null);

        $uaJudge = 'wx'; // TODO judge wx or alipay according to the ua;
        if($uaJudge == 'wx'){
            return $this->redirect('/pay/wx', array(
                'mno' => $mno,
                'tno' => $tno
            ));
        }else if($uaJudge == 'ali'){
            return $this->redirect('/pay/ali', array(
                'mno' => $mno,
                'tno' => $tno
            ));
        }else{
            $this->_end('请使用微信或支付宝进行付款');
        }
    }

    public function actionWx()
    {
        $id_merchant = app()->request->getParam('id_merchant', null);
        $allpay_merchantno = app()->request->getParam('allpay_merchantno', null);
        $allpay_terminalno = app()->request->getParam('allpay_terminalno', null);
        $id_merchant_de = Merchant::decodeMno($id_merchant);
        $amount = app()->request->getPost('amount', null);
        $amount_due = app()->request->getPost('amount_due', null);
        $discount = app()->request->getPost('discount', $this->user->bonus);

        $merchant = Merchant::model()->findByAttributes(array(
            'id_merchant' => $id_merchant_de
        ));
        if(empty($merchant)){
            $this->_end('二维码无效');
        }

        $is_jump = 0;
        app()->WxInterface->switchPlatform($merchant->id_wxplatform);

        $retUserInfo = app()->WxInterface->getCgibinUserInfo($this->user->openid);

        if(isset($retUserInfo->subscribe) && $retUserInfo->subscribe!=1){
            $is_jump = 1;
        }

        if($this->user->is_first_trade != Wxuser::UN_FIRST_TRADE){
            $is_jump = 0;
        }

        $this->render('wx', array(
            'id_merchant' => $id_merchant,
            'allpay_merchantno' => $allpay_merchantno,
            'allpay_terminalno' => $allpay_terminalno,
            'merchant' => $merchant,
            'amount' => $amount,
            'amount_due' => $amount_due,
            'discount' => $discount,
            'is_jump'=>$is_jump,
            'id_wxplatform'=>$merchant->id_wxplatform
        ));
    }

    public function actionIsSubscribe()
    {
        if(app()->request->isAjaxRequest){
            $id_wxplatform = app()->request->getPost('id_wxplatform');
            $openid = app()->request->getPost('openid');
            app()->WxInterface->switchPlatform($id_wxplatform);

            $retUserInfo = app()->WxInterface->getCgibinUserInfo($openid);
            if(isset($retUserInfo->subscribe) && $retUserInfo->subscribe==1) {
                $this->_returnAjax(array(
                    'code' => 200,
                ));
            }
            $this->_returnAjax(array(
                'code' => 500,
            ));
        }
    }

    public function actionWxpayajax()
    {
        $this->_returnAjax(array(
            'result' => false,
            'pay_info_error' => '由于业务原因，摇钱吧的付款功能暂停，恢复时间待定',
        ));

        $id_merchant = app()->request->getParam('id_merchant', null);
        $allpay_terminalno = app()->request->getParam('allpay_terminalno', null);
        $id_merchant_de = Merchant::decodeMno($id_merchant);
        $allpay_terminalno_de = Merchant::decodeTno($allpay_terminalno);

        $merchant = Merchant::model()->findByAttributes(array(
            'id_merchant' => $id_merchant_de
        ));
        if(array_key_exists($merchant->status, Merchant::DISABLE_DESC)){

            $this->_returnAjax(array(
                'result' => false,
                'pay_info_error' => Merchant::DISABLE_DESC[$merchant->status],
            ));
        }

        //是否关注要钱吧
        app()->WxInterface->switchPlatform($merchant->id_wxplatform);
        $is_subscribe = 1;
        try{
            $retUserInfo = app()->WxInterface->getCgibinUserInfo($this->user->openid);

            if(isset($retUserInfo->subscribe) && $retUserInfo->subscribe==1){
                Wxuser::model()->updateByPk($this->user->id_wxuser, array(
                    'nickname'=>$retUserInfo->nickname,
                    'nickname_encode'=>base64_encode($retUserInfo->nickname),
                    'gender'=>$retUserInfo->sex,
                    'avatar_url'=>$retUserInfo->headimgurl,
                    'province'=>$retUserInfo->province,
                    'country'=>$retUserInfo->country,
                    'city'=>$retUserInfo->city,
                    'language'=>$retUserInfo->language,
                ));
            }else{
                $is_subscribe = 0;
                $this->_api_log('subscribe:'.json_encode($retUserInfo),empty($this->user->id_wxuser)?'unkonw':$this->user->id_wxuser,'subscribe');
            }

        }catch (Exception $exception){
            $this->_api_log('error:'.$exception->getMessage(),empty($this->user->id_wxuser)?'unkonw':$this->user->id_wxuser,'subscribe_error');
        }

        $pay_info_error = null;
        $pay_info = null;
        $amount = app()->request->getPost('amount', null); //实际支付
        $amount_due = app()->request->getPost('amount_due', null);//订单金额
        $discount = app()->request->getPost('discount', null);//红包

        if($amount_due > 0){//输入金额
            $tradeDetail = new TradeDetail();
            $tradeDetail->id_wxuser = $this->user->id_wxuser;
            $tradeDetail->id_merchant = $merchant->id_merchant;
            $tradeDetail->out_tradeno = $tradeDetail->genOuttradeno();
            $tradeDetail->amount_due = $amount_due * 100;
            $tradeDetail->allpay_merchantno = $merchant->allpay_mno;
            $tradeDetail->allpay_terminalno = $allpay_terminalno_de;
            $tradeDetail->allpay_biz_channel = TradeDetail::BIZ_CHANNEL_WXPAY;
            $tradeDetail->allpay_biz_type = TradeDetail::BIZ_TYPE_WX_JSPAY;
            $tradeDetail->amount = $amount * 100; //实际支付
            $tradeDetail->is_subscribe = $is_subscribe;//是否关注要钱吧

            if($tradeDetail->amount > 0){ //实际支付
                $tradeDetail->discount = $discount * 100;
            }else{
                $tradeDetail->discount = $tradeDetail->amount_due;
            }

            $tradeDetail->feerate = $merchant->feerate;
            $tradeDetail->rel_fee = round($tradeDetail->amount * $merchant->feerate / 10000, 0);
            $tradeDetail->rel_fee = $tradeDetail->rel_fee < 1? 0 : $tradeDetail->rel_fee;

            //活动期间商家免手续费
            if(strtotime(Merchant::FREE_START_TIME) < strtotime($merchant->createtime) &&
                strtotime($merchant->createtime) < strtotime(Merchant::FREE_END_TIME) &&
                strtotime( $merchant->createtime.'+1 month') > time() &&
                $amount <= Merchant::FREE_MAX_AMOUNT &&
                in_array($merchant->province, Merchant::FREE_PROVINCES)
            ){
                $tradeDetail->fee = 0;
            }else{
                $tradeDetail->fee = $tradeDetail->rel_fee;
            }

            $tradeDetail->trade_status = TradeDetail::TRADE_STATUS_STARTUP;
            $tradeDetail->createtime = date('Y-m-d H:i:s');
            $tradeDetail->save(false);

            if($amount > 0){//实际支付
                $data = json_encode(array(
                    'version' => '2.0',
                    'merchant_id' => $merchant->allpay_mno,
                    'term_id' => $allpay_terminalno_de,
                    'timestamp' => date('YmdHis'),
                    'biz_type' => 'wx.jspay',
                    'biz_content' => array(
                        'trade_no' => $tradeDetail->out_tradeno,
                        'sub_appid' => app()->params['allpay']['sub_appid'],
                        'openid' => $this->user->openid,
                        'total_amount' => $amount,
                        'attach' => $tradeDetail->id_tradedetail,
                        'body' => $merchant->name,
                        'notify_url' => app()->params['allpay']['notify_url'],
                        'time_expire' => date('YmdHis', time() + 360)
                    ),
                    'sign_type' => 'MD5'
                ));
                $token = app()->params['allpay']['token'];
                $sign = SignMd5Helper::genSign($data, $token);

                $curl = new Curl();
                $record_id = $this->user->id_wxuser.time();

                $this->_api_log("Request({$this->user->id_wxuser}): " . json_encode(array(
                        'data' => $data,
                        'sign' => $sign
                    )), $record_id,'wxpay');

                $ret = $curl->postRawExe(app()->params['allpay']['api_url'], array(
                    'data' => $data,
                    'sign' => $sign
                ));

                $this->_api_log("Response({$this->user->id_wxuser}): " .$ret,  $record_id,'wxpay');

                $ret = json_decode($ret, true);
                $ret_data = json_decode($ret['data'], true);

                if(!empty($ret_data['code'] ) && $ret_data['code']  == '100'){
                    $ret_biz_content = $ret_data['biz_content'];
                    $pay_info = $ret_biz_content['pay_info'];

                    $this->_returnAjax(array(
                        'result' => true,
                        'id_tradedetail' => $tradeDetail->id_tradedetail,
                        'pay_info' => json_decode($pay_info)
                    ));
                }elseif($ret_data['code'] == '102'){
                    $pay_info_error = '支付失败';
                    $this->_returnAjax(array(
                        'result' => false,
                        'pay_info_error' => $pay_info_error
                    ));
                }else{
                    $this->_returnAjax(array(
                        'result' => false,
                        'pay_info_error' => $pay_info_error
                    ));
                }
            }else{
                $tradeDetail->amount = $amount * 100;
                $tradeDetail->trade_status = TradeDetail::TRADE_STATUS_SUCCESS;
                $tradeDetail->paytime = $tradeDetail->createtime = date('Y-m-d H:i:s');
                $tradeDetail->save(false);
                //更新该笔交易红包相关字段
                $this->canGetRedPack($tradeDetail);

                //$wxuser = Wxuser::model()->findByPk($this->user->id_wxuser);
                //红包
                if($tradeDetail->discount > 0){

                    $wxuser_bonus_beforedone = $this->user->bonus;
                    $bonus = $this->user->bonus - round($tradeDetail->discount / 100.00, 2);
                    Wxuser::model()->updateByPk($this->user->id_wxuser, array(
                        'bonus'=>$bonus,
                    ));

                    $wxuserBonusUse = new WxuserBonusUse();
                    $wxuserBonusUse->id_wxuser = $tradeDetail->id_wxuser;
                    $wxuserBonusUse->id_merchant = $tradeDetail->id_merchant;
                    $wxuserBonusUse->id_tradedetail = $tradeDetail->id_tradedetail;
                    $wxuserBonusUse->bonus = round($tradeDetail->discount / 100.00, 2);
                    $wxuserBonusUse->wxuser_bonus_afterdone = $bonus;
                    $wxuserBonusUse->wxuser_bonus_beforedone = $wxuser_bonus_beforedone;
                    $wxuserBonusUse->createtime = date('Y-m-d H:i:s');
                    $wxuserBonusUse->save(false);
                }

                if($merchant){
                    //订单金额大于5元，判定激活
                    if($amount_due*100 >= Merchant::MIN_AMOUNT && $merchant->is_active != Merchant::ACTIVE){
                        Merchant::model()->updateByPk($merchant->id_merchant, array(
                            'is_active' => Merchant::ACTIVE,
                            'active_time' => date('Y-m-d H:i:s',time())
                        ));
                    }
                    $balance_change_time = date('Y-m-d H:i:s');
                    $balance_detail_model = new BalanceDetail();
                    $balance_detail_model->type = BalanceDetail::ADD_TYPE;
                    $balance_detail_model->cash = $tradeDetail->amount_due;
                    $balance_detail_model->before_remain_cash = $merchant->remain_cash;
                    $balance_detail_model->after_remain_cash = $merchant->remain_cash + $tradeDetail->amount_due;
                    $balance_detail_model->desc = BalanceDetail::ADD_DESC;
                    $balance_detail_model->create_time = $balance_change_time;
                    $balance_detail_model->id_merchant = $merchant->id_merchant;
                    $balance_detail_model->save(false);

                    if($tradeDetail->fee > 0){
                        $balance_detail_model = new BalanceDetail();
                        $balance_detail_model->type = BalanceDetail::REDUCE_TYPE;
                        $balance_detail_model->cash = $tradeDetail->fee;
                        $balance_detail_model->before_remain_cash = $merchant->remain_cash + $tradeDetail->amount_due;
                        $balance_detail_model->after_remain_cash = $balance_detail_model->before_remain_cash - $tradeDetail->fee;
                        $balance_detail_model->desc = BalanceDetail::REDUCE_DESC;
                        $balance_detail_model->create_time = $balance_change_time;
                        $balance_detail_model->id_merchant = $merchant->id_merchant;
                        $balance_detail_model->save(false);
                    }
                    //更改并发问题
                    app()->db->createCommand('UPDATE merchant set remain_cash = remain_cash + :remain_cash_value WHERE id_merchant = :id_merchant')->execute(array(
                        ':remain_cash_value' => $tradeDetail->amount_due -  $tradeDetail->fee,
                        ':id_merchant' => $merchant->id_merchant,
                    ));

                    //发送模板消息
                    app()->WxInterface->switchPlatform($merchant->id_wxplatform);
                    $not_get_repack = TradeDetail::model()->findBySql("
                              SELECT count(`id_wxuser`) id_wxuser
                              FROM tradedetail 
                              WHERE trade_status=:trade_status AND id_wxuser = :id_wxuser AND get_redpack_type = :get_redpack_type AND is_get_redpack = :no_get_redpack",
                        array(
                            ':id_wxuser'=>$this->user->id_wxuser,
                            ':no_get_redpack'=>TradeDetail::NOT_GET_REDPACK,
                            ':trade_status'=>TradeDetail::TRADE_STATUS_SUCCESS,
                            ':get_redpack_type' => TradeDetail::GET_REDPACK_TYPE1,
                        ));
                    $remark = '';
                    if($tradeDetail->discount>0){
                        $remark .= "\r\n".'该订单使用红包'.round($tradeDetail->discount/100,2).'元';
                    }
                    if($not_get_repack->id_wxuser>0){
                        if($tradeDetail->discount>0) $remark .= ',';
                        $remark .= '您还有'.$not_get_repack->id_wxuser.'笔订单可领红包';
                    }

                    $data =  [
                        "touser"=>$this->user->openid,
                        "template_id"=>app()->params['trade_template_id'],
                        "url"=>"http://".$_SERVER['SERVER_NAME']."/pay/bonushis",

                        "data"=>[
                            "first"=> [
                                "value"=>"恭喜你消费成功！"."\r\n",
                                "color"=>"#173177"
                            ],
                            "keyword1"=>[
                                "value"=>$merchant->name,
                                "color"=>"#173177"
                            ],
                            "keyword2"=> [
                                "value"=>round($tradeDetail->amount_due/100,2)."元",
                                "color"=>"#173177"
                            ],
                            "keyword3"=> [
                                "value"=>$tradeDetail->paytime,
                                "color"=>"#173177"
                            ],
                            "remark"=>[
                                "value"=>$remark,
                                "color"=>"#173177"
                            ]
                        ]
                    ];
                    $curl = new Curl();
                    //记录日志
                    $recode_log_id = $this->user->id_wxuser.time();
                    $this->_api_log('template_request_deta:('.$this->user->id_wxuser.')'.json_encode($data,JSON_UNESCAPED_UNICODE), $recode_log_id,'template_message');
                    //发送模板消息
                    $template_res = app()->WxInterface->sendTemplateMessage($data);
                    //记录日志
                    $this->_api_log('template_reponse_deta:('.$this->user->id_wxuser.')'.json_encode($template_res), $recode_log_id,'template_message');

                    //=======加星
                    if(isset($merchant->is_benefit) && $merchant->is_benefit==1
                        && isset($wxuser->unionid) && !empty(isset($wxuser->unionid))){
                        //记录日志
                        $this->_api_log('start_request_deta:('.$this->user->id_wxuser.')'."{$this->user->unionid}", $recode_log_id,'start');
                        //请求加星

                        $start_result = $curl->postExe(app()->params['add_start_url'],['unionid'=>$this->user->unionid,'id_tradedetail'=>$tradeDetail->id_tradedetail]);
                        //记录日志
                        $this->_api_log('start_reponse_deta:('.$this->user->id_wxuser.')'.json_encode($start_result),$recode_log_id,'start');
                    }
                }

                /*
                 * 发送消息
                 */
                $request_data = json_encode(array(
                    'idMerchant' => $tradeDetail->id_merchant,
                    'amountDue' => $tradeDetail->amount_due,
                    'payType' => 'wx',
                    'payTime' => date('Y-m-d H:i:s'),
                    'outTradeNo' => $tradeDetail->out_tradeno
                ));

                $this->_api_log('request_deta:('.$this->user->id_wxuser.')'.$request_data, $recode_log_id,'message');

                $ret = $curl->postExe(app()->params['message'], array(
                    'data' => $request_data
                ));

                $this->_api_log('reponse_deta('.$this->user->id_wxuser.'):'.$ret, $recode_log_id,'message');
                $this->_returnAjax(array(
                    'id_tradedetail' => $tradeDetail->id_tradedetail,
                    'result' => true,
                    'pay_info_error' => null
                ));
            }
        }else{
            $pay_info_error = '支付金额有误';
            return $this->_returnAjax(array(
                'result' => false,
                'pay_info_error' => $pay_info_error
            ));
        }
    }

    public function actionWxcallback()
    {
        try{
            $postStr = file_get_contents("php://input");

            $this->_log($postStr);

            if(!empty($postStr)){
                $postObj = json_decode($postStr, true);
                $data = json_decode($postObj['data'], true);

                $id_tradedetail = $data['attach'];

                $tradeDetail = TradeDetail::model()->findByAttributes(array(
                    'id_tradedetail' => $id_tradedetail
                ));

                if(!empty($tradeDetail) && $tradeDetail->trade_status != TradeDetail::TRADE_STATUS_SUCCESS){

                    $tradeDetail->channel_tradeno = $data['transaction_id'];
                    $tradeDetail->trade_status = TradeDetail::TRADE_STATUS_SUCCESS;
                    $tradeDetail->paytime = date('Y-m-d H:i:s');
                    $tradeDetail->bank_type = empty($data['bank_type']) ?'0':$data['bank_type'];

                    $tradeDetail->save(false);

                    //更新该笔交易红包相关字段
                    $this->canGetRedPack($tradeDetail);
                    //更新用户是否是第一笔交易
                    $wxuser = Wxuser::model()->findByPk($tradeDetail->id_wxuser);

                    //添加unionid
                    if(isset($data['unionid'])) $wxuser->unionid = $data['unionid'];

                    if($tradeDetail->discount > 0){

                        $wxuser_bonus_beforedone = $wxuser->bonus;
                        $wxuser->bonus -= round($tradeDetail->discount / 100.00, 2);
                        $wxuser->save(false);

                        $wxuserBonusUse = new WxuserBonusUse();
                        $wxuserBonusUse->id_wxuser = $tradeDetail->id_wxuser;
                        $wxuserBonusUse->id_merchant = $tradeDetail->id_merchant;
                        $wxuserBonusUse->id_tradedetail = $tradeDetail->id_tradedetail;
                        $wxuserBonusUse->bonus = round($tradeDetail->discount / 100.00, 2);
                        $wxuserBonusUse->wxuser_bonus_afterdone = $wxuser->bonus;
                        $wxuserBonusUse->wxuser_bonus_beforedone = $wxuser_bonus_beforedone;
                        $wxuserBonusUse->createtime = date('Y-m-d H:i:s');
                        $wxuserBonusUse->save(false);
                    }

                    $merchant = Merchant::model()->findByPk($tradeDetail->id_merchant);

                    if($merchant){
                        //订单金额大于5元，判定激活
                        if($tradeDetail->amount_due*1>=Merchant::MIN_AMOUNT && $merchant->is_active!=Merchant::ACTIVE){
                            Merchant::model()->updateByPk($merchant->id_merchant, array(
                                'is_active' => Merchant::ACTIVE,
                                'active_time' => date('Y-m-d H:i:s',time())
                            ));
                        }

                        $balance_change_time = date('Y-m-d H:i:s');
                        $balance_detail_model = new BalanceDetail();
                        $balance_detail_model->type = BalanceDetail::ADD_TYPE;
                        $balance_detail_model->cash = $tradeDetail->amount_due;
                        $balance_detail_model->before_remain_cash = $merchant->remain_cash;
                        $balance_detail_model->after_remain_cash = $merchant->remain_cash + $tradeDetail->amount_due;
                        $balance_detail_model->desc = BalanceDetail::ADD_DESC;
                        $balance_detail_model->create_time = $balance_change_time;
                        $balance_detail_model->id_merchant = $merchant->id_merchant;
                        $balance_res = $balance_detail_model->save(false);
                        $this->_log('add_balance_detail'.$balance_res);
                        if($tradeDetail->fee > 0){
                            $balance_detail_model = new BalanceDetail();
                            $balance_detail_model->type = BalanceDetail::REDUCE_TYPE;
                            $balance_detail_model->cash = $tradeDetail->fee;
                            $balance_detail_model->before_remain_cash = $merchant->remain_cash + $tradeDetail->amount_due;
                            $balance_detail_model->after_remain_cash = $balance_detail_model->before_remain_cash - $tradeDetail->fee;
                            $balance_detail_model->desc = BalanceDetail::REDUCE_DESC;
                            $balance_detail_model->create_time = $balance_change_time;
                            $balance_detail_model->id_merchant = $merchant->id_merchant;
                            $balance_res = $balance_detail_model->save(false);
                            $this->_log('reduce_balance_detail'.$balance_res);
                        }

                        //更改并发问题
                        app()->db->createCommand('
                            UPDATE merchant set remain_cash = remain_cash + :remain_cash_value WHERE id_merchant = :id_merchant
                        ')->execute(array(
                            ':remain_cash_value' => $tradeDetail->amount_due -  $tradeDetail->fee,
                            ':id_merchant' => $merchant->id_merchant,
                        ));

                    }
                    $message_request_data = json_encode(array(
                        'idMerchant' => $tradeDetail->id_merchant,
                        'amountDue' => $tradeDetail->amount_due,
                        'payType' => 'wx',
                        'payTime' => date('Y-m-d H:i:s'),
                        'outTradeNo' => $tradeDetail->out_tradeno
                    ));
                    $uid = create_uuid().$wxuser->id_wxuser;
                    //纪录消息发送请求数据
                    $this->_api_log('request_data:('.$wxuser->id_wxuser.')'.$message_request_data, $uid,'message');

                    $curl = new Curl();
                    $ret = $curl->postExe(app()->params['message'], array(
                        'data' => $message_request_data
                    ));

                    //纪录消息发送接收数据
                    $this->_api_log('request_data:('.$wxuser->id_wxuser.')'.$ret, $uid,'message');

                    //发送模板消息
                    app()->WxInterface->switchPlatform();

                    $not_get_repack = TradeDetail::model()->findBySql("
                              SELECT count(`id_wxuser`) id_wxuser
                              FROM tradedetail 
                              WHERE trade_status=:trade_status AND id_wxuser = :id_wxuser AND get_redpack_type = :get_redpack_type AND is_get_redpack = :no_get_redpack",
                        array(
                            ':id_wxuser'=>$wxuser->id_wxuser,
                            ':get_redpack'=>TradeDetail::GET_REDPACK,
                            ':trade_status'=>TradeDetail::TRADE_STATUS_SUCCESS,
                            ':get_redpack_type' => TradeDetail::GET_REDPACK_TYPE1,
                        ));

                    $remark='';
                    if(isset($tradeDetail->discount)&& $tradeDetail->discount>0){
                        $remark .= "\r\n".'该订单使用红包'.round($tradeDetail->discount/100,2).'元';
                    }
                    if(isset($not_get_repack->id_wxuser) && $not_get_repack->id_wxuser>0){
                        if($tradeDetail->discount>0) $remark .= ',';
                        $remark .= '您还有'.$not_get_repack->id_wxuser.'笔订单可领红包';
                    }

                    $data =  [
                        "touser"=>$wxuser->openid,
                        "template_id"=>app()->params['trade_template_id'],
                        "url"=>"http://".$_SERVER['SERVER_NAME']."/pay/bonushis",

                        "data"=>[
                            "first"=> [
                                "value"=>"恭喜你消费成功！",
                                "color"=>"#173177"
                            ],
                            "keyword1"=>[
                                "value"=>$merchant->name,
                                "color"=>"#173177"
                            ],
                            "keyword2"=> [
                                "value"=>round($tradeDetail->amount_due/100,2)."元",
                                "color"=>"#173177"
                            ],
                            "keyword3"=> [
                                "value"=>$tradeDetail->paytime,
                                "color"=>"#173177"
                            ],
                            "remark"=>[
                                "value"=>$remark,
                                "color"=>"#173177"
                            ]
                        ]
                    ];
                    $this->_log('TEST_6'.json_encode($data));
                    //记录日志
                    $this->_api_log('template_request_deta:('.$wxuser->id_wxuser.')'.json_encode($data), $uid,'template_message');

                    $template_res = app()->WxInterface->sendTemplateMessage($data);

                    $this->_api_log('template_reponse_deta:('.$wxuser->id_wxuser.')'.json_encode($template_res), $uid,'template_message');

                    // 加星
                    if(isset($merchant->is_benefit) && $merchant->is_benefit==1
                        && isset($wxuser->unionid) && !empty(isset($wxuser->unionid))){
                        //记录日志
                        $this->_api_log('start_request_deta:('.$wxuser->id_wxuser.')'."{$wxuser->unionid}", $uid,'start');
                        //请求加星
                        $start_result = $curl->postExe(app()->params['add_start_url'],['unionid'=>$wxuser->unionid,'id_tradedetail'=>$id_tradedetail]);

                        //记录日志
                        $this->_api_log('start_reponse_deta:('.$wxuser->id_wxuser.')'.json_encode($start_result),$uid,'start');

                    }
                    echo 'success';
                }
            }
        }catch (Exception $e){

            $this->_log($e->getMessage());
        }
    }

    public function actionWxsuccess()
    {
        $id_tradedetail = app()->request->getParam('id_tradedetail', null);
        $id_merchant = app()->request->getParam('id_merchant', null);
        $merchant_name = app()->request->getParam('merchant_name', null);

        $tradeDetail = TradeDetail::model()->findByPk($id_tradedetail);

        if($tradeDetail){
            $wxuser = Wxuser::model()->findByPk($tradeDetail->id_wxuser);
            $result = $this->canGetRedPack($tradeDetail,false);
            $is_can_get = $result['is_can_get'];
            $desc_in_view = $result['desc'];
            $getdiscount_data = array(
                'status' => 0,
                'qrcodeurl' => '',
                'idmp' => '',
                'id_wxuser_double' => '',
                'idmpinforecord' => '',
            );
            $show_modal_data = array(
                'show_type' => '0', //1开的modal 2红包金额的modal 3翻倍卡的modal
                'amount' => '',
            );

            $can_request = true;

            $get_amount = 0;
            if($tradeDetail->is_get_redpack == TradeDetail::GET_REDPACK){
                $bonus_record = WxuserBonusGet::model()->findByAttributes(array(
                    'id_wxuser' => $tradeDetail->id_wxuser,
                    'id_tradedetail' => $tradeDetail->id_tradedetail
                ));
                if(!empty($bonus_record)){
                    $show_modal_data['amount'] = $bonus_record->bonus;
                    $show_modal_data['show_type'] = '2';
                    $show_modal_data['id_mapinfo'] = '2';
                }
                $is_can_get = TradeDetail::CANNOT_GET_REDPACK;
                $can_request = false;
            }else{
                $wxuser_double_model = WxuserDouble::model()->findByAttributes(array(
                    'id_tradedetail' => $tradeDetail->id_tradedetail,
                    'id_wxuser' =>  $tradeDetail->id_wxuser ,
                ));

                if(!empty($wxuser_double_model)){
                    $is_can_get = TradeDetail::CANNOT_GET_REDPACK;
                    $getdiscount_data['id_wxuser_double'] = $wxuser_double_model->id_wxuser_double;
                    $show_modal_data['show_type'] = '3';
                    $can_request = false;
                }
            }

            if($can_request && $is_can_get == TradeDetail::CAN_GET_REDPACK){
                $show_modal_data['show_type'] = '1';
                //请求获取红包接口
                $result = $this->getRedPack(array(
                    'idWxuser' => $wxuser->id_wxuser,
                    'idTradeDetail' => $tradeDetail->id_tradedetail,
                    'idMerchant'=> $tradeDetail->id_merchant,
                    'nickname' => $wxuser->nickname_encode,
                    'headImgUrl' => $wxuser->avatar_url,
                    'openid' => $wxuser->openid,
                    'unionId' => $wxuser->unionid,
                    'language' => $wxuser->language,
                    'province' => base64_encode($wxuser->province),
                    'country' => base64_encode($wxuser->country),
                    'city' => base64_encode($wxuser->city),
                    'sex' => $wxuser->gender,
                    'type' => 'get',
                    'api_url' => app()->params['get_qrcode'],
                    'api_type' =>'get_qrcode',
                    'api_place' => 'pay_success'
                ), $wxuser);
                if($result['api_result'] == 200 && !empty($result['status'])){
                    if($result['status'] == TradeDetail::GET_REDPACK_TYPE1 &&
                        !empty($result['qrcodeurl']) &&
                        !empty($result['idmp']) &&
                        !empty($result['idmpinforecord'])
                    ){
                        $getdiscount_data['status'] = TradeDetail::GET_REDPACK_TYPE1;
                        $getdiscount_data['qrcodeurl'] = $result['qrcodeurl'];
                        $getdiscount_data['idmp'] = $result['idmp'];
                        $getdiscount_data['idmpinforecord'] = $result['idmpinforecord'];

                        /*$wxuser_double_model = WxuserDouble::model()->findByAttributes(array(
                            'id_wxuser' =>  $tradeDetail->id_wxuser,
                            'status' => WxuserDouble::STATUS_UNUSE,
                        ));
                        if(!empty($wxuser_double_model)){
                            $is_can_get = TradeDetail::CANNOT_GET_REDPACK;
                            $getdiscount_data['id_wxuser_double'] = $wxuser_double_model->id_wxuser_double;
                        }*/

                    }elseif($result['status'] == TradeDetail::GET_REDPACK_TYPE5){
                        $getdiscount_data['status'] = TradeDetail::GET_REDPACK_TYPE5;
                    }
                }
            }
            //记录日志
            $this->_api_log('is_jump_wxsuccess(can_get_redpack->'.$is_can_get.';id_tradedetail->'.$tradeDetail->id_tradedetail.')',$wxuser->id_wxuser,'is_jump_wxsuccess');

            $this->render('wxsuccess', array(
                'tradeDetail' => $tradeDetail,
                'id_merchant' =>$id_merchant,
                'merchant_name' => $merchant_name,
                'is_can_get' => $is_can_get,
                'get_discount_data' => $getdiscount_data,
                'desc_in_view' => $desc_in_view,
                'show_data' => $show_modal_data,
                'wxuser' => $wxuser,
            ));
        }
    }

    public function actionGetprize()
    {
        $id_tradedetail = $_POST['id_tradedetail'];
        $id_wxuser = $_POST['id_wxuser'];
        $uid = create_uuid();
        try{
            $wxuser = Wxuser::model()->findByPk($id_wxuser);
            $tradedetail = TradeDetail::model()->findByPk($id_tradedetail);
            if(empty($wxuser) || empty($tradedetail) || $tradedetail->id_wxuser != $wxuser->id_wxuser){

                $this->_api_log('unkonwPrams', $uid, 'error');
                return $this->_returnAjax(array('code' => '403' , 'msg' => 'unkonwPrams'));
            }

            $wxuser_double_model = WxuserDouble::model()->findByAttributes(array(
                'id_tradedetail' => $id_tradedetail,
                'id_wxuser' => $id_wxuser ,
                'status' =>  WxuserDouble::STATUS_UNUSE ,
            ));
            if(empty($wxuser_double_model)){
                $wxuser_double_model = new WxuserDouble();
                $wxuser_double_model->id_tradedetail = $id_tradedetail;
                $wxuser_double_model->id_wxuser = $id_wxuser;
                $wxuser_double_model->createtime = date('Y-m-d H:i:s');
                $wxuser_double = $wxuser_double_model->save(false);

                TradeDetail::model()->updateByPk($id_tradedetail,array(
                    'get_redpack_type' => TradeDetail::GET_REDPACK_TYPE6,
                    'get_redpack_desc' => TradeDetail::GET_REDPACK_DESC[TradeDetail::GET_REDPACK_TYPE6],
                ));
            }

            return $this->_returnAjax(array('code' => 200,'id_wxuser_double' => $wxuser_double));
        }catch (Exception $exception){
            $this->_api_log('getdoubleprize:'.$exception->getMessage(), $uid, 'error');
            return $this->_returnAjax(array('code' => 200,'id_wxuser_double' => '0'));
        }
    }

    protected function canGetRedPack($tradeDetail, $is_update = true)
    {
        //同一商户规定时间内是否达到领取次数
        $strattime = date('Y-m-d H:i:s',strtotime($tradeDetail->createtime)- TradeDetail::LIMI_TIME);

        $bonus_gets = WxuserBonusGet::model()->findAllBySql("SELECT * FROM wxuser_bonus_get WHERE id_wxuser=:id_wxuser AND id_merchant=:id_merchant AND createtime >= :strattime AND createtime <= :endtime AND request_no != :request_no", array(
            ':id_wxuser' => $tradeDetail->id_wxuser,
            ':id_merchant' => $tradeDetail->id_merchant,
            ':strattime' => $strattime,
            ':endtime' => $tradeDetail->createtime,
            ':request_no' => TradeDetail::SECOND_REQUEST_NO
        ));
        //是否是有过红包记录
        $bonus_gets_record  = WxuserBonusGet::model()->findByAttributes(array(
            'id_wxuser' => $tradeDetail->id_wxuser,
        ));
        //是否可以领取红包
        $is_get_redpack = TradeDetail::CANNOT_GET_REDPACK;

        if((empty($bonus_gets_record) || $tradeDetail->is_subscribe == TradeDetail::SUBSCRIBE) && $tradeDetail->amount_due >= TradeDetail::LIMIT_AMOUNT && count($bonus_gets) < TradeDetail::LIMI_GET_TIMES){
            $is_get_redpack = TradeDetail::CAN_GET_REDPACK;

        }

        $detail = array('get_redpack_type' => TradeDetail::GET_REDPACK_TYPE1, 'get_redpack_desc' => TradeDetail::GET_REDPACK_DESC[TradeDetail::GET_REDPACK_TYPE1]);
        if($tradeDetail->amount_due < TradeDetail::LIMIT_AMOUNT){
            $detail = array('get_redpack_type' => TradeDetail::GET_REDPACK_TYPE3, 'get_redpack_desc' => TradeDetail::GET_REDPACK_DESC[TradeDetail::GET_REDPACK_TYPE3]);

        }elseif(count($bonus_gets) >= TradeDetail::LIMI_GET_TIMES){
            $detail = array('get_redpack_type' => TradeDetail::GET_REDPACK_TYPE4, 'get_redpack_desc' => TradeDetail::GET_REDPACK_DESC[TradeDetail::GET_REDPACK_TYPE4]);

        }elseif (count($bonus_gets_record) != 0 && $tradeDetail->is_subscribe != TradeDetail::SUBSCRIBE){
            $detail = array('get_redpack_type' => TradeDetail::GET_REDPACK_TYPE2, 'get_redpack_desc' => TradeDetail::GET_REDPACK_DESC[TradeDetail::GET_REDPACK_TYPE2]);
        }

        if($is_update){
            TradeDetail::model()->updateByPk($tradeDetail->id_tradedetail, array(
                'get_redpack_type' => $detail['get_redpack_type'],
                'get_redpack_desc' => $detail['get_redpack_desc'],
            ));
        }

        return array(
            'desc' => TradeDetail::getDescByType($detail['get_redpack_type']),
            'is_can_get' => $is_get_redpack,
        );
    }

    public function actionBonushis()
    {
        $arr_type = ['gets','uses','trades'];
        $post_type = app()->request->getPost('type',null);

        //分页
        if(app()->request->isPostRequest && isset($post_type) && in_array($post_type,$arr_type)){
            $isend = 0;
            //$gets_isend = 0;$uses_isend=0;$trades_isend=0;
            $page = app()->request->getPost('page',null);
            $every_count = TradeDetail::default_limit;

            $condition = 'id_wxuser = :id_wxuser';
            $condition_arr = array('id_wxuser' => $this->user->id_wxuser);
            switch ($post_type){
                case 'trades':
                    $sum = TradeDetail::model()->count($condition,$condition_arr);
                    break;
                case 'uses':
                    $sum = WxuserBonusUse::model()->count($condition,$condition_arr);
                    break;
                case 'gets':
                    $sum = WxuserBonusGet::model()->count($condition,$condition_arr);
                    break;
            }


            $total_page = ceil($sum/$every_count);

            $page = app()->request->getPost('page', 0);

            $page = $page<0 ?0:$page;

            if($page>=$total_page){
                $page = (int) $total_page;
                $isend = 1;
            }
            switch ($post_type){
                case 'trades':
                    $data = TradeDetail::model()->getTradeByUid(
                        $this->user->id_wxuser,
                        $page*$every_count,
                        TradeDetail::default_limit
                    );
                    break;
                case 'uses':
                    $data = WxuserBonusUse::model()->getUsedBonusByUid(
                        $this->user->id_wxuser,
                        $page*$every_count,
                        TradeDetail::default_limit
                    );
                    break;
                case 'gets':
                    $data = WxuserBonusGet::model()->getGetBonusByUid(
                        $this->user->id_wxuser,
                        $page*$every_count,
                        TradeDetail::default_limit);
                    break;
            }

            return $this->renderPartial('bonushis_list',array(
                'data' => $data,
                'isend'=>$isend,
                'type'=>$post_type,
            ));


            //end-page
        }else{
            $trades = TradeDetail::model()->getTradeByUid($this->user->id_wxuser,0,TradeDetail::default_limit);

            $uses = WxuserBonusUse::model()->getUsedBonusByUid($this->user->id_wxuser,0,TradeDetail::default_limit);

            $gets = WxuserBonusGet::model()->getGetBonusByUid($this->user->id_wxuser,0,TradeDetail::default_limit);

            $trades_desc = TradeDetail::model()->findBySql(
                'SELECT count(id_wxuser) id_wxuser,sum(amount_due) amount_due
                FROM tradedetail 
                WHERE id_wxuser = :id_wxuser AND trade_status=:trade_status
                ', array(

                'id_wxuser' => $this->user->id_wxuser,
                'trade_status' => '1',
            ));


            $trades_desc_arr['count'] = '共交易'.$trades_desc->id_wxuser.'次';
            $trades_desc_arr['sum'] = round($trades_desc->amount_due/100,2);


            $uses_desc = WxuserBonusUse::model()->findBySql(
                'SELECT count(id_wxuser) id_wxuser, sum(bonus) bonus
                FROM wxuser_bonus_use 
                WHERE id_wxuser = :id_wxuser
                ', array(

                'id_wxuser' => $this->user->id_wxuser,
            ));
            $uses_desc_arr['count'] = '共使用红包'.$uses_desc->id_wxuser.'次';
            $uses_desc_arr['sum'] = $uses_desc->bonus ?$uses_desc->bonus:0;

            $gets_desc = WxuserBonusGet::model()->findBySql(
                'SELECT count(id_wxuser) id_wxuser,sum(bonus) bonus
                FROM wxuser_bonus_get 
                WHERE id_wxuser = :id_wxuser
                ', array(
                'id_wxuser' => $this->user->id_wxuser,
            ));
            $gets_desc_arr['count'] = '共获得红包'.$gets_desc->id_wxuser.'次';
            $gets_desc_arr['sum'] = $gets_desc->bonus ?$gets_desc->bonus:0;

            $wxuser = Wxuser::model()->findByPk($this->user->id_wxuser);

            $this->render('bonushis', array(
                'trades'=>$trades,
                'uses' => $uses,
                'wxuser' => $wxuser,
                'gets' => $gets,
                'default_limit'=>TradeDetail::default_limit,
                'top_desc'=>array(
                    'trades_desc'=>$trades_desc_arr,
                    'gets_desc'=>$gets_desc_arr,
                    'uses_desc'=>$uses_desc_arr
                )
            ));
        }

    }

    public function actionDeliverhis()
    {
        $id_wxuser = app()->request->getParam('id_wxuser', null);
        $idmp = app()->request->getParam('idmp', null);
        $action = app()->request->getParam('action', null);
        $id_tradedetail = app()->request->getParam('id_tradedetail', null);
        $uid = create_uuid();
        try{
            if($idmp && $action && $id_wxuser){
                /*$wxuser = Wxuser::model()->findByPk($id_wxuser);
                if($wxuser){
                    $wxuser->discount_tutorial = 1;
                    $wxuser->save(false);
                }*/

                $mpDeliver = new MpDeliverHis();
                $mpDeliver->id_wxuser = $id_wxuser;
                $mpDeliver->idmp = $idmp;
                $mpDeliver->action = $action;
                $mpDeliver->id_tradedetail = $id_tradedetail;
                $mpDeliver->createtime = date('Y-m-d H:i:s');
                $mpDeliver->save();

                $this->_returnAjax('success');
            }
        }catch (Exception $exception){
            $this->_api_log('actionDeliverhis:'.$exception->getMessage(), $uid, 'error');
            $this->_returnAjax('error');
        }
    }

    public function actionMchreturn()
    {

        die();
        $id_tradedetail = app()->request->getParam('id_tradedetail', null);

        $tradeDetail = TradeDetail::model()->findByPk($id_tradedetail);
        if($tradeDetail){
            $merchant = Merchant::model()->findByPk($tradeDetail->id_merchant);
            if($merchant){
                $tradeDetail->mchreturn = $merchant->mchreturn;
                $tradeDetail->save(false);
                $merchant->remain_cash += $tradeDetail->amount_due -  $tradeDetail->fee + $tradeDetail->mchreturn;
                $merchant->save(false);
            }
        }
    }

    protected function _api_log($info = null, $uid='?', $save_name = 'api')
    {
        $log_file = dirname(__FILE__) . '/logs/'.$save_name.date('Ymd').'.log';

        $info = empty($info)? '' : $info;
        $info = date('Y-m-d H:i:s - ')  . '('.$uid.')' . $info . "\n";

        $handler = fopen($log_file, 'a+');
        fputs($handler, $info);
        fclose($handler);
    }

    //写入日志数据
    protected function writeApiLog($case, $str, $api_type ,$uid)
    {
        $this->_api_log($case.':'.$str, $uid,'api_'.$api_type);
    }

    /*
     * 获取是否推荐公众号和红包api
     */
    public function actionGetApiData()
    {
        $result = $this->getRedPack($_POST);

        return $this->_returnAjax($result);
    }

    protected function getRedPack($data = array(), $wxuser='')
    {
        if(empty($data['idWxuser'])){
            $this->_api_log("error(id_wxuser参数错误)",'unknow','api_error');
            return array('api_result'=>403,'message'=>'参数错误');
        }

        $uid = create_uuid().'_'.$data['idWxuser'];

        if(empty($data['idTradeDetail'])){
            $this->_api_log("error(idTradeDetail参数错误)", $uid ,'api_error');
            return array('api_result'=>403,'message'=>'参数错误');
        }

        if(empty($data['idMerchant']) || empty($data['api_type']) || !in_array($data['api_type'], array('get_qrcode', 'get_isdiscount'))){
            $this->_api_log("error(idMerchant-api_type参数错误)", $uid,'api_error');
            return array('api_result'=>403,'message'=>'参数错误');
        }

        try{
            $merchant = Merchant::model()->findByPk($data['idMerchant']);
            if(empty($wxuser)){
                $wxuser = Wxuser::model()->findByPk($data['idWxuser']);
            }


            app()->WxInterface->switchPlatform($merchant->id_wxplatform);
            $retUserInfo = app()->WxInterface->getCgibinUserInfo($wxuser->openid);
            if(isset($retUserInfo->subscribe) && $retUserInfo->subscribe==1){
                $data['nickname'] = empty($retUserInfo->nickname)? $wxuser->nickname_encode: base64_encode($retUserInfo->nickname);
                $data['sex'] = empty($retUserInfo->sex)? $wxuser->gender: $retUserInfo->sex;
                $data['province'] = empty($retUserInfo->province)? base64_encode($wxuser->province): base64_encode($retUserInfo->province);
                $data['city'] = empty($retUserInfo->city)? base64_encode($wxuser->city): base64_encode($retUserInfo->city);
                $data['country'] = empty($retUserInfo->country)? base64_encode($wxuser->country): base64_encode($retUserInfo->country);
                $data['headImgUrl'] = empty($retUserInfo->headimgurl)? $wxuser->avatar_url: $retUserInfo->headimgurl;
                $data['language'] = empty($retUserInfo->language)? $wxuser->language: $retUserInfo->language;
            }

            $this->writeApiLog("request_data",json_encode($data, JSON_UNESCAPED_UNICODE),$data['api_type'],$uid);

            $curl = new Curl();
            if($data['api_type'] == 'get_isdiscount'){
                $result = $curl->getExe(app()->params['get_isdiscount'], $data);
            }else{
                $result = $curl->getExe(app()->params['get_qrcode'], $data);
            }

            $this->writeApiLog("response_data",$result,$data['api_type'],$uid);

            $result_arr = json_decode($result, true);

            if(!empty($result_arr['discount']) && $result_arr['discount']>0){
                //更新用户是否是第一次领到红包
                if ($wxuser->is_first_trade != Wxuser::UN_FIRST_TRADE){
                    Wxuser::model()->updateByPk($wxuser->id_wxuser,array(
                        'is_first_trade'=>Wxuser::UN_FIRST_TRADE,
                    ));
                }
                //清除非今天的记录
                app()->db->createCommand('
                            UPDATE redpack_riskcontrol set is_del = :del_status WHERE createtime < :today_time
                        ')->execute(array(
                    ':today_time' => date('Y-m-d'),
                    ':del_status' => RedpackRiskcontrol::DEL_STATUS,
                ));
                //添加风控记录
                $risk_model = RedpackRiskcontrol::model()->findByAttributes(array(
                    'id_merchant' => $merchant->id_merchant,
                    'id_wxuser' => $wxuser->id_wxuser,
                    'is_del' => RedpackRiskcontrol::UNDEL_STATUS,
                ));
                if(!empty($risk_model)){
                    app()->db->createCommand('
                            UPDATE redpack_riskcontrol set times = times + :add_times, updatetime = :updatetime WHERE id_redpack_riskcontrol = :id_redpack_riskcontrol
                        ')->execute(array(
                        ':add_times' => RedpackRiskcontrol::ADD_TIMES,
                        ':updatetime' => date('Y-m-d H:i:s'),
                        ':id_redpack_riskcontrol' => $risk_model->id_redpack_riskcontrol,
                    ));

                    $risk_count = RedpackRiskcontrol::model()->findBySql('
                    SELECT count(id_merchant) as id_merchant FROM  redpack_riskcontrol WHERE id_merchant=:id_merchant AND times > :limit_times AND is_del = :undel_status
                ', array(
                        ':id_merchant' => $merchant->id_merchant,
                        ':limit_times' => app()->params['risk']['limit_times'],
                        ':undel_status' => RedpackRiskcontrol::UNDEL_STATUS,
                    ));

                    if($risk_count->id_merchant >= app()->params['risk']['risk_value']){
                        Merchant::model()->updateByPk($merchant->id_merchant, array(
                            'exception_status' => Merchant::EXCEPTION_STATUS_RED,
                        ));
                    }elseif ($risk_count->id_merchant >= app()->params['risk']['warning_value']){
                        Merchant::model()->updateByPk($merchant->id_merchant, array(
                            'exception_status' => Merchant::EXCEPTION_STATUS_YELLOW,
                        ));
                    }
                }else{
                    $time = date('Y-m-d H:i:s');
                    $risk_model = new RedpackRiskcontrol();
                    $risk_model->id_merchant = $merchant->id_merchant;
                    $risk_model->id_wxuser = $wxuser->id_wxuser;
                    $risk_model->createtime = $time;
                    $risk_model->updatetime = $time;
                    $risk_model->save();
                }
            }

            if(is_array($result_arr)){
                $mer_arr = array_merge(array(
                    'api_result'=>200,
                    'message'=>'ok',
                ),$result_arr);
            }else{
                $this->_api_log("error(请求返回数据类型错误)", $uid,'api_error');
                $mer_arr = array('api_result'=>501,'message'=>'');
            }
            return $mer_arr;

        }catch (Exception $e){
            $this->_api_log("error(系统出错)".$e->getMessage(), '?','api_error');
            return array('api_result'=>500,'message'=>$e->getMessage());
        }
    }

    public function actionJsError()
    {
        $post_data = $_POST;
        $this->_api_log("error:".empty($post_data['err_msg'])?'':$post_data['err_msg'].'id_tradedetail'.empty($post_data['id_tradedetail'])?'':$post_data['id_tradedetail'],empty($post_data['id_wxuser'])?'0':$post_data['id_wxuser'],'api_error');
        return true;
    }

    public function actionGetredpackrule()
    {
        return $this->render('get_redpack_rule');
    }

    //扫码
    public function actionHelper()
    {
        $coderesult = app()->request->getParam('coderesult', null);
        if($coderesult){
            $explode = explode('id_merchant=', $coderesult);
            if(isset($explode[1])){
                $id_merchant_en = $explode[1];
                $id_merchant_de = Merchant::decodeMno($id_merchant_en);

                $this->_returnAjax(array(
                    'id_merchant_en' => $id_merchant_en,
                    'id_merchant_de' => $id_merchant_de,
                    'time' => date('H:i:s'),
                ));
            }


            die();
        }

        app()->WxInterface->switchPlatform();

        $this->render('helper');
    }

    public function accessRules()
    {
        $isLoginExpression = 'false';
        $id_merchant = null;
        $id_wxplatform = Wxplatform::DEFAULT_ID;

        $mno = app()->request->getParam('mno', null);
        $mnoDe = Merchant::decodeMno($mno);
        $merchant = Merchant::model()->findByPk($mnoDe);
        if($merchant){
            $id_wxplatform = $merchant->id_wxplatform;
        }
        if(app()->user->getIsWxLogin($id_wxplatform)){
            $isLoginExpression = 'true';
            $isLoginRedirect = null;
        }else{
            $isLoginExpression = 'false';
            $isLoginRedirect = url('/wxauth/wxlogin', array(
                'callback_landing' => app()->request->getUrl(),
                'id_wxplatform' => $id_wxplatform
            ));
        }

        //跳过微信登录
        /*if($isLoginExpression=='false'){
            $this->user=Wxuser::model()->findByPk(1947);
            $isLoginExpression = 'true';
        }*/

        return array(
            array(
                'allow',
                'actions' => array('wx', 'wxsuccess', 'bonushis', 'deliverhis'),
                'expression' => $isLoginExpression,
                'redirect' => $isLoginRedirect
            ),

            array(
                'allow',
                'users' => array('*'),
            )
        );
    }
}